﻿using Aliyun.OSS;
using Google.Protobuf.WellKnownTypes;
using LeafCore.Commons.Enums;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace LeafCore.Components.SSO
{
    public class OSSService : IOSSService
    {
        private readonly ILogger<OSSService> _logger;
        private readonly OSSServiceOptions _options;

        public OSSService(
            ILoggerFactory loggerFactory,
            OSSServiceOptions options)
        {
            _logger = loggerFactory.CreateLogger<OSSService>();
            _options = options;
        }
      public async  Task<(bool, string)> UploadFileAsync(string fileName, IFormFile file, BucketNameType bucketNameType, string filePath)
        {
            //桶路径
            string bucketName = bucketNameType.ToDescriptionOrString();

            if (string.IsNullOrEmpty(fileName))
            {
                return (false, "文件名称错误");
            }

            if (string.IsNullOrEmpty(bucketName))
            {
                return (false, "储存路径不能为空");
            }

            // 创建OssClient实例。
            var client = new OssClient(_options.Endpoint, _options.AccessKeyId, _options.AccessKeySecret);

            if (!client.DoesBucketExist(bucketName))
                client.CreateBucket(new CreateBucketRequest(bucketName) { ACL = CannedAccessControlList.PublicReadWrite });

            //配置Bucket加密。
            var request = new SetBucketEncryptionRequest(bucketName, "AES256", null);
            client.SetBucketEncryption(request);

            using (var memoryStream = new MemoryStream())
            {
                await file.CopyToAsync(memoryStream).ConfigureAwait(false);
                memoryStream.Seek(0, SeekOrigin.Begin);

                var rs = client.PutObject(bucketName, fileName, memoryStream);
                if (rs.HttpStatusCode != System.Net.HttpStatusCode.OK)
                    return (false, "上传文件失败，请重试");
            }

            string fileWork = _options.FileWork.Replace("@FilePath", bucketName);
            return (true, $"{fileWork}/{fileName}");
        }
    }
}
